package com.audiocn.poster;

import java.io.File;

import com.audiocn.Utils.Log;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class TLCYClearService extends Service {

	public static Thread thread;
	public static boolean isGoOn = true;

	public Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			TLCYClearService.this.onDestroy();
			thread.stop();
			super.handleMessage(msg);
		}

	};

	static TLCYClearService tlcycs = null;

	@Override
	public void onCreate() {
		super.onCreate();
		Log.e("TLCYClearService", isGoOn + "");
		if (!isGoOn) {
			this.stopSelf();
		} else {
			tlcycs = this;
			Log.e("TLCYClearService", "TLCYClearService has created!");
			thread = new Thread() {
				boolean flag = false;

				@Override
				public void run() {
					Log.e("TLCYClearService", "TLCYClearService start clear!");
					try {
						File dir = new File(Configs.tlcyImgPath);
						if (!dir.exists()) {
							return;
						}
						File[] fils = dir.listFiles();
						if (fils != null) {
							for (int i = 0; i < fils.length; i++) {
								Thread.sleep(10);
								if (!flag && isGoOn) {
									Log.e("TLCYClearService", "clearFile:"
											+ fils[i].getName());
									fils[i].delete();
								} else {
									break;
								}
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					Log.e("TLCYClearService",
							"TLCYClearService clearOpera has complete!");
					if (tlcycs != null) {
						tlcycs.onDestroy();
					}
				}

				@Override
				public void interrupt() {
					flag = true;
					super.interrupt();
				}

			};
			thread.start();
		}
	}

	public static TLCYClearService getTLCYClearService() {
		return tlcycs;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		tlcycs = null;
		if (thread != null && thread.isAlive()) {
			thread.interrupt();
		}
		Log.e("TLCYClearService", "TLCYClearService has canceled..01");
		this.stopSelf();
		Log.e("TLCYClearService", "TLCYClearService has canceled..02");
		if (isGoOn) {
			System.exit(0);
		}
		isGoOn = true;
		Log.e("TLCYClearService", "TLCYClearService has canceled..03");
		super.onDestroy();
		Log.e("TLCYClearService", "TLCYClearService has canceled..04");
	}

}
